#include <chrono>
#include <iostream>
#include <thread>
#include "ThreadPool.h"
#include <functional>
#include "stdlib.h"
using std::cout;
using std::endl;

using Elemtype = std::function<void()>;
ThreadPool::ThreadPool(int threadnum,int task_capa)
    :_threadnum(threadnum)
    ,threads()
    ,_capacity(task_capa)
    ,_taskQue(_capacity)
     ,isExit(false)
{

}

ThreadPool::~ThreadPool(){}

void ThreadPool::start(){
    for(int i = 0;i < _threadnum;++i){
        threads.push_back(thread(&ThreadPool::doTask,this));
    }
}
void ThreadPool::stop(){
    while(!_taskQue.empty()){ //等任务全部被取走
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    isExit = true; //子线程入口函数的结束标志位
    _taskQue.wakeup(); //唤醒所有在条件变量等待
    for(auto &th:threads){
        th.join();
    }
}
void ThreadPool::addTask(Elemtype &&ele){
    if(ele){
        _taskQue.push(std::move(ele)); 
    }
}
/* ElemType getTask(); //从任务队列总取出一个任务 */
void ThreadPool::doTask(){ //子线程的入口函数
    while(!isExit){
        //从任务堆列取任务
        Elemtype ele = _taskQue.pop();
        //执行任务
        if(ele){
            ele();
        }
    }
}
